package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.AccountInfo;
import com.example.mapper.AccountInfoMapper;
import com.example.response.R;
import com.example.service.AccountInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
public class AccountInfoServiceImpl
        extends ServiceImpl<AccountInfoMapper, AccountInfo>
        implements AccountInfoService, UserDetailsService {

    @Autowired
    private AccountInfoMapper accountInfoMapper;


    /**
     * 重写Userdetails中的loadUserByUsername方法去查询数据库中的
     * @param account
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        //查询用户信息
        LambdaQueryWrapper<AccountInfo> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AccountInfo::getAccount,account);
        AccountInfo accountInfo = accountInfoMapper.selectOne(lqw);
        System.out.println(accountInfo);

        //没有查询到用户就抛出异常
        if (ObjectUtils.isEmpty(accountInfo)){
            throw new RuntimeException("账号获取密码错误");
        }

        //TODO 查询对应的权限信息
        List<String> list = new ArrayList<>(Arrays.asList("test","admin"));

        //把数据封装成UserDetails
        return new LoginAccountInfo(accountInfo, list, null);
    }

    @Override
    public R<Map<String, String>> login(AccountInfo accountInfo) {
        return null;
    }


    /**
     * 查询所有用户信息
     **/
    @Override
    public R queryAccount() {
        List<AccountInfo> accountInfos = accountInfoMapper.selectList(null);
        return R.success(accountInfos);
    }

}

